package com.example.mvc.service;

import com.example.mvc.bean.User;
import com.example.mvc.mapper.UserMapper;
import com.example.mvc.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class UserService {

    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * 登录方法
     * @param username
     * @param password
     * @return
     */

    public User login(String username, String password){
        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4. 调用方法
        User user = mapper.select(username, password);
        //释放资源
        sqlSession.close();

        return  user;
    }

    public boolean register(User registerUser){
        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4.  判断用户名是否存在
        User user = mapper.selectByUsername(registerUser.getUsername());
        if (user==null){//用户不存在，可以注册
            //插入用户的信息
            mapper.add(registerUser);
            //提交
            sqlSession.commit();
        }
        //释放资源
        sqlSession.close();

         //查到的用户为空就是可以注册，返回true。否则就不可以注册
        return  user==null;

    }
}
